from docx import Document
from docx.oxml.ns import qn
from docx.shared import Pt,RGBColor
import os
# 英文罗马字体成功
import re
# from _add_hyperlink import add_hyperlink

def txt2docx(txtpath):
#     txtpath=txtpath.replace("\\",'/')
    document = Document()

    document.styles['Normal'].font.name = u'宋体'
    document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
    document.styles['Normal'].font.name = 'Times New Roman'#这样只有英文转为新罗马【已经成功！！！！！！！！！！！！！！！！！】
    document.styles['Normal'].font.size = Pt(10.5)
    document.styles['Normal'].font.color.rgb = RGBColor(0,0,0)


    paragraph = document.add_paragraph()
    run = paragraph.add_run()
    run.font.name = 'Times New Roman' 
#     run.font.name=u'Cambria'
    run.font.color.rgb = RGBColor(0,0,0)
#     run._element.rPr.rFonts.set(qn('w:eastAsia'), u'Cambria')
    run._element.rPr.rFonts.set(qn('w:eastAsia'), 'Times New Roman')

    # 打开txt文件，并写入document中
    # f = open(r"C:\Users\zhou\PycharmProjects\test\test.txt","r",encoding='UTF-8')   # 注意编码类型
    # f = open(r"C:\Users\King\Desktop\sci\aluminum%20sphere_zh.txt","r",encoding='UTF-8')
    f=open(txtpath,"r",encoding='UTF-8')
    line = f.readline()
    while line:
      document.add_paragraph(line)
#       if "http" in line:
#           url=re.findall(r'https.*',line)# re.findall是列表
#           add_hyperlink(paragraph,url[0],'链接')# 在找到的line后一段添加【必须有空行，否则都在末尾】【现在是都在开头？？？】
      
      line = f.readline()

    f.close()

    print('任务完成！！')

    # 保存文档
    # document.save(r'C:\Users\King\Desktop\sci\aluminum%20sphere_zh.docx')
    docxpath=txtpath.replace("txt","docx")
    document.save(docxpath)
# path_=r"C:\Users\King\Desktop\sci\microfludic preparation sphere_zh.txt"#.replace("\\",'/')
# txt2docx(path_)